﻿using Microsoft.AspNetCore.Mvc;
using OnlineFIR.Models;
using OnlineFIR.Storage;
using System.Text.Json;
using System.Text;
using OnlineFIR.Mechanic;
using OnlineFIR.Utilities;
using Nancy.Json;

namespace OnlineFIR.Controllers
{
    public class GameController : Controller
    {

        public GameController()
        {
        }

        //private static bool flag;
        public IActionResult Game(string identifier,int x=-1,int y=-1)
        {
            if (identifier == null || identifier=="")
            {
                string newId = SlotStorage.Add();
                ViewBag.identifier = newId;
                identifier = newId;
            }
            else
            {
                ViewBag.identifier = identifier;
            }
            Slot nowSlot = SlotStorage.Find(identifier);
            Map map = nowSlot.map;
            if (map.IsValid(x, y))
            {
                if (!nowSlot.isOver)
                {
                    map.Set(x, y, 1);
                    nowSlot.isOver = WinCheck.Check(map, x, y);
                }
                if (!nowSlot.isOver)
                {
                    FIRAi1 ai = new FIRAi1(map);
                    Point decision = ai.Decide();
                    map.Set(decision, 2);
                    nowSlot.isOver = WinCheck.Check(map, decision.x, decision.y);
                }
            }
            byte[][] res = map.Get();
            JavaScriptSerializer json = new JavaScriptSerializer();
            ViewBag.map = json.Serialize(res);
            return View();
        }
    }
}
